import URLImage from '@/components/URLImage'
import Konva from 'konva'
import { useRef, useState } from 'react'
import { Group, Layer, Line, Stage } from 'react-konva'

interface IRgba {
  r: number
  g: number
  b: number
  a: number
}

export default function View() {
  const [color, setColor] = useState('')
  const stageRef = useRef<Konva.Stage>()

  const handleMouseDown = e => {
    const currentLayer = e.target.getLayer()
    if (currentLayer === null) {
      return
    }

    const { x, y } = e.target.getStage().getPointerPosition()
    const pixelRatio = currentLayer.getCanvas().getPixelRatio()
    const canvas = currentLayer.getNativeCanvasElement()

    const { data } = canvas.getContext('2d').getImageData(x * pixelRatio, y * pixelRatio, 1, 1)

    const r = data[0]
    const g = data[1]
    const b = data[2]
    const a = data[3] / 255

    const rgba = { r, g, b, a }
    const hex = rbgaObjToHex(rgba)
    setColor(hex)
  }

  // 十进制转化为16进制
  const hex = (n: number) => {
    return `0${n.toString(16)}`.slice(-2)
  }

  const rbgaObjToHex = (rgba: IRgba) => {
    let { r, g, b } = rgba
    const { a } = rgba
    r = Math.floor(r * a)
    g = Math.floor(g * a)
    b = Math.floor(b * a)
    return `#${hex(r)}${hex(g)}${hex(b)}`
  }

  return (
    <div>
      <input type='color' value={color} readOnly />
      <Stage width={window.innerWidth} height={window.innerHeight} ref={stageRef} onMouseDown={handleMouseDown}>
        <Layer>
          <Group>
            <URLImage src='https://konvajs.org/assets/yoda.jpg' x={100} y={100} />
            <Line
              listening={false}
              scaleX={2}
              scaleY={2}
              x={100}
              y={100}
              points={[40, 80, 400, 480]}
              stroke='#009988'
              strokeWidth={10}
              tension={0.5}
              lineCap='round'
              lineJoin='round'
            />
            <Line
              x={100}
              y={100}
              points={[40, 80, 400, 480]}
              stroke='#009988'
              strokeWidth={10}
              tension={0.5}
              lineCap='round'
              lineJoin='round'
            />
            <Line
              points={[20, 20, 200, 200]}
              stroke='#df4b26'
              strokeWidth={10}
              tension={0.5}
              lineCap='round'
              lineJoin='round'
            />
          </Group>
        </Layer>
      </Stage>
    </div>
  )
}
